<?php

namespace App\Http\Controllers\Common;

use App\Package\Code\Code;
use Illuminate\Http\Request;
use App\Package\Message\Message;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;

/**
 * 文件上传逻辑
 *
 * Date: 2018/06/01
 * @author Tenny
 * @package App\Http\Controllers\Common
 */
class UploadController extends Controller
{
    /**
     * 上传文件
     *
     * Date: 2018/06/01
     * @author Tenny
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function upload(Request $request)
    {
        $this->validate($request, [
            'file' => 'required',
            'relation' => [
                'required',
                Rule::in(array_keys(config('system.upload.relation')))
            ]
        ], [
            'file.required' => '请选择要上传的文件',
            'relation.required' => '请指定文件关系',
            'relation.in' => '文件关联关系不存在',
        ]);
        $file = $request->file('file');
        if ($file->isValid()) {
            $path = $file->store($request->get('relation'), 'public');
            return success(['path' => Storage::url($path)]);
        }
        return failed('文件上传失败');
    }

    /**
     * 删除文件
     * Date: 2018/06/01
     * @author Tenny
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request)
    {
        $this->validate($request, [
            'path' => 'required',
        ], [
            'path.required' => '请选择要删除文件的路径',
        ]);
        $path = $request->file('path');
        Storage::disk('public')->delete($path);
        return $this->deleted();
    }
}
